package com.ostrich.cloud.ostrichUserService.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ostrich.cloud.common.result.PageResult;
import com.ostrich.cloud.common.result.Result;
import com.ostrich.cloud.ostrichPermission.client.PermissionClient;
import com.ostrich.cloud.ostrichPermission.client.param.AddUserParam;
import com.ostrich.cloud.ostrichUserService.common.CustomerResultCode;
import com.ostrich.cloud.ostrichUserService.common.RoleLevel;
import com.ostrich.cloud.ostrichUserService.common.exception.CusException;
import com.ostrich.cloud.ostrichUserService.common.stateEnum.CluStateEnum;
import com.ostrich.cloud.ostrichUserService.common.utils.Algorithm;
import com.ostrich.cloud.ostrichUserService.infra.mapper.BusinessmanMapper;
import com.ostrich.cloud.ostrichUserService.infra.mapper.UserParentMapper;
import com.ostrich.cloud.ostrichUserService.infra.model.Businessman;
import com.ostrich.cloud.ostrichUserService.infra.model.Customer;
import com.ostrich.cloud.ostrichUserService.infra.model.UserParent;
import com.ostrich.cloud.ostrichUserService.service.BusinessmanService;
import com.ostrich.ostrichUserService.dto.CustomerDto;
import com.ostrich.ostrichUserService.dto.bussiness.BusinessmanDto;
import com.ostrich.ostrichUserService.param.bussiness.LoginBusParam;
import com.ostrich.ostrichUserService.param.bussiness.RegBussinessmanParam;
import com.ostrich.ostrichUserService.param.bussiness.UpdateBusParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-10-26
 */
@Service
@Slf4j
public class BusinessmanServiceImpl extends ServiceImpl<BusinessmanMapper, Businessman> implements BusinessmanService {
    @Resource
    private PermissionClient permissionClient;

    @Resource
    private BusinessmanMapper businessmanMapper;

    @Resource
    private UserParentMapper userParentMapper;

    @Resource
    private RedissonClient redissonClient;

    private static  String KEYS = "BusHarvest";


    @Override
    public void addBusiness(RegBussinessmanParam regBus) {
        AddUserParam userParam = new AddUserParam();
        userParam.setUsername(regBus.getUsername());
        /**
         * 密码进行加密
         */
        userParam.setPassword(Algorithm.md5(regBus.getPassword()));
        userParam.setRoleId(RoleLevel.STORE);
        Result result = permissionClient.addUser(userParam);
        if (result.getCode()!=200){
            throw new CusException(CustomerResultCode.USERNAME_COPY_EXCEPTION);
        }
        Integer parentId = (Integer) result.getData();

        Businessman businessman = BeanUtil.copyProperties(regBus, Businessman.class);
        businessman.setBusinessmanStatus(CluStateEnum.NORMAL.getCode());
        businessman.setParentId(parentId);

        int businessmanId = businessmanMapper.insert(businessman);
        log.info("返回的商家id{}",businessman.getBusinessmanId());
        /*
         添加商家地址的经纬度到redis
         */
        RGeo<Object> geo = redissonClient.getGeo(KEYS);
        long add = geo.add(Double.parseDouble(regBus.getLatitude()),
                Double.parseDouble(regBus.getLogitude()), businessman.getBusinessmanId());

    }

    @Override
    public void updateBusState(Integer parentId, String status) {
        UpdateWrapper<UserParent> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("parent_id",parentId)
                .set("status",status);
        userParentMapper.update(null,updateWrapper);
        UpdateWrapper<Businessman> updateCuWrapper = new UpdateWrapper<>();
        updateCuWrapper.eq("parent_id",parentId)
                .set("businessman_status",status);
        businessmanMapper.update(null,updateCuWrapper);
        /**
         * 更新redis缓存设置
         */

        if (CluStateEnum.CANCEL.getCode().equals(status)){
            Businessman businessman = businessmanMapper.selectOne(new QueryWrapper<Businessman>().eq("parent_id", parentId));

            RScoredSortedSet<Object> scoredSortedSet = redissonClient.getScoredSortedSet(KEYS);
            scoredSortedSet.remove(businessman.getBusinessmanId());
        }
    }

    @Override
    public UserParent businessmanLogin(LoginBusParam loginBusParam) {
        log.info("加密的密码是{}",Algorithm.md5(loginBusParam.getPassword()));
        QueryWrapper<UserParent> query = new QueryWrapper<>();
        query.eq("username",loginBusParam.getUsername())
                .eq("password",Algorithm.md5(loginBusParam.getPassword()));
        UserParent userParent = userParentMapper.selectOne(query);
        if (userParent==null){
            throw new CusException(CustomerResultCode.PASSWORD_EXCEPTION);
        }
        if(CluStateEnum.CANCEL.getCode().equals(userParent.getStatus())){
            throw new CusException(CustomerResultCode.CANCEL_EXCEPTION);
        }

        return userParent;
    }

    @Override
    public PageResult<BusinessmanDto> getAllBusiness(Integer current, Integer size, String status) {
        PageResult<BusinessmanDto> pageResult = new PageResult<>();
        Page<BusinessmanDto> page = new Page<>(current,size);

        IPage<BusinessmanDto> allBusiness = businessmanMapper.getAllBusiness(page, status);



        pageResult.setElements(allBusiness.getRecords());

        log.info("当前页{}",allBusiness.getCurrent());
        pageResult.setPage(allBusiness.getCurrent());

        log.info("每页的大小{}",allBusiness.getSize());
        pageResult.setPageSize(allBusiness.getSize());

        log.info("总数{}",allBusiness.getTotal());
        pageResult.setTotal(allBusiness.getTotal());

        log.info("总的页数{}",allBusiness.getPages());
        pageResult.setTotalPage(allBusiness.getPages());


        return pageResult;

    }

    @Override
    public void updateBusinessMessage(Businessman bus) {
        UpdateWrapper<Businessman> businessmanUpdateWrapper = new UpdateWrapper<>();
        Businessman businessman = businessmanMapper.selectOne(new QueryWrapper<Businessman>()
                .eq("parent_Id",bus.getParentId()));



        log.info(">>>>>>>>>>>>>>>>>zheshigesha{}-------------{}<<<<<<<<<",bus.getBusinessmanName()!=null && !("".equals(bus.getBusinessmanName())),bus.getBusinessmanName());

        businessmanUpdateWrapper.eq("parent_id",bus.getParentId())
                .set(bus.getPhone()!=null,"phone",bus.getPhone())
                .set(bus.getBusinessmanName()!=null && !("".equals(bus.getBusinessmanName())),"businessman_name",bus.getBusinessmanName())
                .set(bus.getBankNumber()!=null,"bank_number",bus.getBankNumber())
                .set(bus.getLatitude()!=null && !("".equals(bus.getLatitude())),"latitude",bus.getLatitude())
                .set(bus.getLogitude()!=null && !("".equals(bus.getLogitude())),"logitude",bus.getLogitude())
                .set(bus.getLocationInfo()!=null && !("".equals(bus.getLocationInfo())),"location_info",bus.getLocationInfo());

        businessmanMapper.update(null,businessmanUpdateWrapper);

    }

    @Override
    public   Map<Double, Businessman> getAllBusinessByLocation(String latitude, String logitude,Double radius) {
        RGeo<Object> geo = redissonClient.getGeo(KEYS);

        Map<Object, Double> objectDoubleMap = geo.radiusWithDistance(Double.parseDouble(latitude),
                Double.parseDouble(logitude),
                radius, GeoUnit.KILOMETERS,GeoOrder.ASC);//附近的距离
       if (objectDoubleMap.size()==0){
           throw new CusException("你的附近"+radius+"公里没有商家",1007);
       }
        Set<Object> keySet = objectDoubleMap.keySet();
        Map<Double, Businessman> hashMap = new HashMap<>();
        log.info("返回的keySet{}",keySet);

        QueryWrapper<Businessman> businessmanQueryWrapper = new QueryWrapper<>();
        businessmanQueryWrapper.in("businessman_id",
                keySet);

        List<Businessman> businessmen = businessmanMapper.selectList(businessmanQueryWrapper);
        for (Businessman bus: businessmen) {

            hashMap.put(objectDoubleMap.get(bus.getBusinessmanId()),bus);

        }
//        ArrayList<Map.Entry<Businessman, Double>> entries = new ArrayList<>(hashMap.entrySet());
//        Collections.sort(entries, (o1, o2) -> {
//            return (int)(o1.getValue() - o2.getValue())*10000;
//        });
//        log.info("排序后的结果{}",entries);
//        hashMap.clear();
//        for (Map.Entry<Businessman, Double> s:entries) {
//            hashMap.put(s.getKey(),s.getValue());
//        }
        log.info("返回的hashmap的值是{}",hashMap);
        return hashMap;
    }

    @Override
    public Map<Double, Businessman> getOneBusinessByLocation(String latitude, String logitud) {
        RGeo<Object> geo = redissonClient.getGeo(KEYS);

        Map<Object, Double> objectDoubleMap = geo.radiusWithDistance(Double.parseDouble(latitude),
                Double.parseDouble(logitud),
               5, GeoUnit.KILOMETERS,GeoOrder.ASC,1);//附近的距离

        if (objectDoubleMap.size()==0){
            throw new CusException(CustomerResultCode.NEIGHBORHOOD_NO_BUSINESSMAN);
        }
        Set<Object> keySet = objectDoubleMap.keySet();
        Map<Double, Businessman> hashMap = new HashMap<>();
        log.info("返回的keySet{}",keySet);

        QueryWrapper<Businessman> businessmanQueryWrapper = new QueryWrapper<>();
        businessmanQueryWrapper.in("businessman_id",
                keySet);

        List<Businessman> businessmen = businessmanMapper.selectList(businessmanQueryWrapper);
        for (Businessman bus: businessmen) {
            hashMap.put(objectDoubleMap.get(bus.getBusinessmanId()),bus);
        }
        return hashMap;

    }


}
